<template>
  <div class="goods-type-wrapper">
    <div class="flex goods-type-line">
      <!-- <div class="goods-type-title">{{ paramData.options.title }}</div> -->
      <div class="flex goods-type-labels">
        <div :class="{ active: current == item.value }" class="goods-type-item" v-for="(item, index) in labels"
          :key="index" @click="handleClickLabel(item.name, item.value)">
          {{ item.name }}
        </div>
      </div>
    </div>
    <!-- 商品部分 -->
    <div class="only-goods-list flex-j-sb">
      <div class="only-goods-list-item" v-for="(item, index) in list" :key="index" @click="openModel(item)">
        <!-- <div class="goods-img">
          <Carousel :height="175" autoplay :autoplay-speed="5000" v-if="item.typeImage">
            <CarouselItem v-for="(it, index) in item.typeImage.split(',')" :key="index">
              <div style="width: 100%;height: 100%;">
                <img style="width: 100%;height: 100%;" :src="baseUrl + it" />
              </div>
            </CarouselItem>
          </Carousel>
          <img style="width: 100%;height: 175px;" src="" v-else />
        </div> -->
        <div class="goods-price">
          <div class="user">
            <Avatar v-if="item.user && item.user.avatarUrl" :src="baseUrl + item.user.avatarUrl" />
            <Avatar v-else src="https://i.loli.net/2017/08/21/599a521472424.jpg" />
            <span class="user-name" style="margin-left: 10px;">{{ item.user ? item.user.nickName : '用户昵称' }}</span>
          </div>
          <!-- <span class="price">{{ item.price | unitPrice("￥") }}</span> -->

          <span class="state" :style="{ color: getState(item).type }">{{ getState(item).label }}</span>
        </div>
        <div>
          <div class="goods-name wes-2">{{ item.title }}</div>
          <div class="goods-desc">需求类型：{{ getType(item.type) }}</div>
          <div class="goods-desc">起止时间：{{ formatDate(item.startTime) }} ~ {{ formatDate(item.endTime) }}</div>
          <div class="goods-desc whiteSpace">需求描述：{{ item.content }}</div>
          <div class="goods-desc">发布时间：{{ item.createTime }}</div>
        </div>

        <!-- 查看 -->
        <div class="white-shadow">
          <div class="search">去查看</div>
        </div>
      </div>
    </div>
    <div class="goodsButton">
      <Page :total="Page.total" @on-change="PageChange" />
    </div>
    <Modal v-model="modal" :title="title" width="70%">
      <Form ref="formValidates" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <!-- <Row> -->
        <!-- <Col span="12"> -->
        <FormItem label="需求类型:">
          <div>{{ getType(formValidate.type) }}</div>
        </FormItem>
        <!-- </Col>
          <Col span="12"> -->
        <FormItem label="需求标题:">
          {{ formValidate.title }}
        </FormItem>
        <!-- </Col>
          <Col span="12"> -->
        <FormItem label="需求起止时间:">
          {{ formValidate.startTime }} - {{ formValidate.endTime }}
        </FormItem>
        <!-- </Col>
          <Col span="12"> -->
        <FormItem label="附件上传:" v-if="formValidate.file != null">
          <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear"
            tag="ul">
            <li :key="file" class="el-upload-list__item ele-upload-list__item-content"
              v-for="(file) in formValidate.file.split(',')">
              <div>
                <span>
                  <Icon type="md-list-box" /> {{ getFileName(file) }}
                </span>
              </div>
            </li>
          </transition-group>
        </FormItem>
        <!-- </Col>
          <Col span="12"> -->
        <FormItem label="需求描述:">
          {{ formValidate.content }}
        </FormItem>
        <!-- </Col>
          <Col span="12"> -->
        <FormItem label="备注:">
          {{ formValidate.remark }}
        </FormItem>
        <!-- </Col>
          <Col span="12"> -->
        <FormItem label="其他需求:">
          {{ formValidate.other }}
        </FormItem>
        <!-- </Col> -->
        <!-- </Row> -->
      </Form>
      <div slot="footer">
        <Button @click="modal = false">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" @click="modal = false">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  saveDesired, getDesiredList, getDesiredById, getOrderTypeList,
  getOrderListByUserId, saveOrderApportion, getOrderApportionByUserId,
  updateDesired, auditOrderFeedback, saveEvaluate, orderAfterSale,
  writerDesiredList, getOrderRecords
} from "@/api/writer/index.js";
import storage from "@/plugins/storage";
import { EventBus } from '@/plugins/EventBus';
export default {
  name: "goods",
  computed: {
    shouldShowFormItem() {
      return this.title === '基础详情' && (this.formValidate.order || !this.formValidate.order);
    },
    selectedState: {
      get() {
        return this.formValidate.order ? this.formValidate.order.state : this.formValidate.state;
      },
      set(newValue) {
        if (this.formValidate.order) {
          this.formValidate.order.state = newValue;
        } else {
          this.formValidate.state = newValue;
        }
      }
    },
    isUserRole() {
      return this.roles === 'user';
    },
    isWriterRole() {
      return this.roles === 'writers';
    },
    isFileUploadDisabled() {
      return this.formValidate.state !== '5' && (!this.formValidate.order || this.formValidate.order.state !== 30);
    },
    isInputDisabled() {
      return this.formValidate.state !== '5' && (!this.formValidate.order || this.formValidate.order.state !== 30);
    },
    showInputTip() {
      return this.roles === 'user' && this.formValidate.order && this.formValidate.order.state === 30;
    }
  },
  data() {
    return {
      baseUrl: BASE.API_DEV.buyer,
      current: "-1",
      modal: false,//需求弹窗
      modal1: false,//需求弹窗
      QRCode: false,//付款弹窗
      title: "新增需求",
      labels: [
        {
          name: "全部订单",
          value: -1,
        },
        {
          name: "发布中",
          value: 0,
        },
        {
          name: "进行中",
          value: 50,
        },
        {
          name: "已完成",
          value: 70,
        },
      ],
      single: false,
      formValidate: {
        type: null,
        title: '',
        content: '',
        file: '',
        price: null,
        remark: '',
        other: '',
        startTime: '',
        endTime: '',
      },
      feedbackFrom: {
        feedbackContent: '',
        feedbackFile: [],
        remark: ''
      },
      clickType: [],
      date: [],//日期
      defaultList: [],//附件列表
      feedbackList: [],//反馈文件列表
      type: [],//需求类型
      ruleValidate: {
        type: [
          { required: true, message: '请选择需求类型', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入需求标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入需求描述', trigger: 'blur' }
        ],
        file: [
          { required: true, message: '请选择附件上传', trigger: 'change' }
        ],
        // feedbackFile: [
        //   { required: true, message: '请选择附件上传', trigger: 'change' }
        // ],
        price: [
          { required: true, message: '请输入佣金金额', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入整数或两位小数',
            trigger: 'change'
          }
        ],
        startTime: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
      },
      loading: false,
      roles: "",
      list: [],
      typeList: [
        {
          label: "发布中",
          value: 30,
        },
        {
          label: "进行中",
          value: 50,
        },
        {
          label: "已完成",
          value: 70,
        },
      ],
      Page: {
        total: 0,
        pageNum: 1,
        pageSize: 12,
      },
      evaluation: false,
      evaluationModel: {
        image: null,
        // star: 0,
        content: '',
        clickType: ''
      },
      paymentType: '',//付款类型
      afterSales: false,//售后
      afterSalesContent: '',//售后原因
      modalRejectShow: false,
    };
  },
  created() {
    EventBus.$on('message', this.GetDesiredList);
  },
  beforeDestroy() {
    EventBus.$off('message', this.GetDesiredList);
  },
  watch: {},
  mounted() {
    if (storage.getItem("roles")) {
      this.roles = storage.getItem("roles")
    }
    this.GetDesiredList()
    this.GetOrderTypeList()
    // this.GetDesiredListPending()

  },
  methods: {
    formatDate(dateStr) {
      // 如果 dateStr 存在，分割字符串取日期部分
      if (dateStr) {
        return dateStr.split(' ')[0];
      }
      // 如果 dateStr 不存在，返回 '//'
      return '//';
    },
    //获取状态
    getState(item) {
      if (!item.order && item.state <= 30) {
        return {
          label: '发布中',
          type: '#73a5f2'
        }
      } else if (item.order && item.order.state >=70) {
        return {
          label: '已完成',
          type: 'black'
        }
      } else {
        return {
          label: '进行中',
          type: 'green'
        }
      }
    },

    // 筛选出当前分类下的商品
    handleClickLabel(name, val) {
      console.log(name, val);
      this.current = val;
      this.Page.pageNum = 1
      this.GetDesiredList()
    },
    handleSubmit(name, state) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (!this.single) {
            this.$Message.error('请勾选协议!');
            return
          }
          if (this.roles == 'user') {
            this.formValidate.file = this.defaultList.map(x => x.url).join(',')
            saveDesired({
              ...this.formValidate,
              state: state == 0 ? '0' : this.formValidate.state,
            }).then(res => {
              console.log(res, "保存需求订单");
              if (res.code == 200) {
                this.$Message.success('保存成功!');
                this.modal = false;
                this.single = false
              }
            })
          } else {
            this.feedbackFrom.feedbackFile = this.feedbackList.map(x => x.url).join(',')
            console.log(this.feedbackFrom, this.feedbackList);

            saveOrderApportion({ ...this.feedbackFrom }).then(res => {
              console.log(res, "保存需求订单");
              if (res.code == 200) {
                this.$Message.success('保存成功!');
                this.modal = false;
                this.single = false
                setTimeout(() => {
                  this.$refs.feedbackFrom.resetFields();
                }, 1000);
              }
            })
          }
        } else {
          this.$Message.error('请填写完整信息!');
        }
      })
    },
    cancel() {
      this.$refs.formValidates.resetFields();
      this.modal = false;
      this.single = false
      this.afterSales = false
      this.evaluation = false
      this.QRCode = false
      this.modalRejectShow = false
    },
    openModel(item) {
      this.GetOrderTypeList()
      // this.GetOrderRecords(item.id)
      this.GetDesiredById(item.id)
    },
    reset() {
      this.formValidate = {
        type: null,
        title: '',
        content: '',
        file: [],
        price: null,
        remark: '',
        other: '',
        startTime: '',
        endTime: '',
      }
      this.feedbackFrom = {
        feedbackContent: '',
        feedbackFile: [],
        remark: ''
      }
    },
    //获取需求列表
    GetDesiredList(title) {
      if (title) {
        console.log(title, "title");
      }

      const params = {
        pageNum: this.Page.pageNum,
        pageSize: this.Page.pageSize,
        title: title,
        // type: this.current,
        state: Number(this.current),
        // identity: this.roles == 'user' ? '0' : '1',
      }
      console.log(params);

      getDesiredList(params).then((res) => {
        if (res.code == 200) {
          this.list = res.data.records;
          this.Page.total = res.data.total
          // this.Page.pageNum = res.data.pages
          // this.Page.pageSize = res.data.size
        }
      });
    },
    //获取需求待审核列表
    GetDesiredListPending() {
      const params = {
        pageNum: this.Page.pageNum,
        pageSize: this.Page.pageSize,
        state: Number(this.current),
        identity: this.roles == 'user' ? '0' : '1',
      }
      writerDesiredList(params).then((res) => {
        if (res.code == 200) {
          console.log(res, "res");
          this.list.push(...res.rows);
          this.Page.total += res.rows.total
        }
      })
    },
    GetOrderListByUserId() {
      const params = {
        pageNum: this.Page.pageNum,
        pageSize: this.Page.pageSize,
        state: Number(this.current),
        type: this.roles == 'user' ? '0' : '20',
      }
      getOrderListByUserId(params).then((res) => {
        if (res.code == 200) {
          this.list = res.data.records.map(el => {
            return {
              ...el.desired,
              allotPrice: el.allotPrice
            }
          });
        }
      })
    },
    //获取需求详情
    GetDesiredById(id) {
      const params = {
        desiredId: id,
      }
      getDesiredById(params).then((res) => {
        if (res.code == 200 && res.data) {
          res.data.price = res.data.price + ''
          // res.data.type = res.data.type + ''
          res.data.state = res.data.state + ''
          this.modal = true;
          this.title = "基础详情";
          this.single = false
          if (res.data.type) {
            this.clickType = res.data.type.split(',')
          }
          if (res.data.order) {
            res.data.order.state = res.data.order.state + ''
            // this.GetOrderApportionByUserId(res.data.order.id)
          }
          this.date = [res.data.startTime, res.data.endTime]
          this.formValidate = res.data
          if (res.data.file) {
            this.defaultList = res.data.file.split(',').map(x => {
              return {
                name: this.getFileName(x),
                url: x,
              }
            })
          }
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    //获取需求信息
    GetOrderRecords(id) {
      const params = {
        desiredId: id,
      }
      getOrderRecords(params).then((res) => {
        console.log(res, "res");

        if (res.code == 200) {
          if (res.data.length != 0) {
            this.$Notice.success({
              title: '提示',
              duration: 5,
              desc: res.data[res.data.length - 1].content
            });
          }
        }
      })
    },
    GetOrderApportionByUserId(id) {
      const params = {
        orderId: id,
        identity: this.roles == 'user' ? '0' : '1',
      }
      getOrderApportionByUserId(params).then((res) => {
        if (res.code == 200) {
          if (res.data.feedbackFile) {
            this.feedbackList = res.data.feedbackFile.split(',').map(x => {
              return {
                name: this.getFileName(x),
                url: x,
              }
            })
          }
          this.feedbackFrom = res.data
        }
      })
    },
    //获取订单类型
    GetOrderTypeList() {
      getOrderTypeList().then(res => {
        this.type = res.data.map(x => {
          return {
            label: x.name,
            value: x.id + ''
          }
        })
      })
    },
    //日期选择
    handleClickDate(val) {
      console.log(val, "val");
      this.formValidate.startTime = val[0]
      this.formValidate.endTime = val[1]
    },
    //上传附件
    FileUploadInput(file) {
      console.log(file, "file");
    },
    FileUploadInput1(file) {
      this.feedbackList.push({
        name: this.getFileName(file),
        url: file
      })
    },
    FileUploadInput2(file) {
      this.evaluationList = []
      console.log(file, "file");
      this.evaluationList.push({
        name: this.getFileName(file),
        url: file
      })
    },
    //页面切换
    PageChange(e) {
      console.log(e, 'eeee');
      this.Page.pageNum = e;
      this.GetDesiredList()
    },
    getClass(val) {
      if (!this.modal) return "";
      const currentState = this.formValidate.order ? this.formValidate.order.state : this.formValidate.state;
      return val == currentState ? "active" : val <= currentState ? "expired" : "";
    },
    getType(val) {
      if (!val) return '';
      return val.split(',')
        .map(x => {
          const found = this.type.find(y => y.value == x);
          return found ? found.label : '';
        })
        .join(',');
    },
    payment() {
      // console.log();

      updateDesired({ id: this.formValidate.id }).then(res => {
        if (res.code == 200) {
          this.$Message.success('付款成功!');
          this.QRCode = false
          this.modal = false
          this.GetDesiredList()
        }
      })
    },
    clickTypeFun(val) {
      console.log(val, "val");
      this.formValidate.type = val.join(',')
    },
    //下载附件
    downloadLocalFile() {
      console.log(this.formValidate.file, "this.formValidate.file");
      let file = this.formValidate.file.split(',')
      file.forEach(item => {
        window.open(this.baseUrl + item, '_blank')
      })

    },
    // downloadLocalFile() {
    //   // 创建一个 <a> 标签
    //   const a = document.createElement('a');
    //   // 设置文件的下载地址，这里假设文件在 public 目录下
    //   a.href = '/static/example.pdf'; 
    //   // 设置下载的文件名
    //   a.download = 'example.pdf';
    //   // 模拟点击 <a> 标签触发下载
    //   a.click();
    //   // 移除 <a> 标签
    //   a.remove();
    // }
    //去审核
    ToReview(state) {
      this.feedbackFrom.state = state
      console.log(this.feedbackFrom, "this.feedbackFrom");
      auditOrderFeedback(this.feedbackFrom).then(res => {
        if (res.code == 200) {
          this.$Message.success('操作成功!');
          this.modal = false
        }
      })
    },
    //去评价
    evaluationFun() {
      // if (!this.evaluationModel.star) {
      //   this.$Message.error('请选择星级!');
      //   return
      // }
      this.evaluationModel.image = this.evaluationList.map(x => x.url).join(',')
      saveEvaluate({
        ...this.evaluationModel,
        orderId: this.formValidate.id
      }).then(res => {
        if (res.code == 200) {
          this.$Message.success('操作成功!');
          this.evaluation = false
          setTimeout(() => {
            this.evaluationModel = {
              image: [],
              // star: 0,
              content: ''
            }
          }, 1000);

        }
      })
    },
    //去售后
    GetorderAfterSale() {
      orderAfterSale({
        orderId: this.formValidate.id
      }).then(res => {
        if (res.code == 200) {
          this.$Message.success('已向客服提交售后申请，等待客服审核!');
        }
      })
    },
  },
};
</script>

<style scoped lang="scss">
.white-shadow {
  width: 287px;
  height: 122px;
  border-radius: 0px 0px 10px 10px;
  opacity: 1;
  position: absolute;
  bottom: 0;
  left: 0;
  opacity: 0;
  display: flex;
  justify-content: center;
  transition: 0.35s;
  align-items: center;
  background: linear-gradient(180deg,
      rgba(252, 252, 252, 0.58) -50%,
      #ffffff 99%);
}

.search {
  width: 143px;
  height: 45px;
  border-radius: 22.5px;
  opacity: 1;
  font-size: 20px;
  font-weight: normal;
  text-align: center;
  letter-spacing: 0px;
  line-height: 45px;
  color: #ffffff;
  background: $theme_color;
}

.only-goods-list {
  // display: flex;
  // flex-wrap: wrap;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.only-goods-list-item {
  // padding-top: 30px;
  width: 287px;
  height: 245px;
  border-radius: 9.8px;
  opacity: 1;
  margin-bottom: 14.3px;
  cursor: pointer;
  background: #ffffff;
  transition: all 0.4s ease;
  box-shadow: 0px 1px 13px 0px #e5e5e5;
  position: relative;
  display: flex;
  flex-direction: column;
  // align-items: center;
  overflow: hidden;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0px 1px 14px 0px #c5c5c5;

    >.white-shadow {
      opacity: 1;
    }

    >.goods-img {
      >img {
        opacity: 0.85 !important;
        object-fit: cover;

      }
    }
  }
}

.goods-img {
  margin-bottom: 9.8px;
  text-align: center;
  // padding: 0 10px;
  width: 100%;

  >img {
    transition: all 0.4s ease;
    width: auto;
    max-height: 183px;

  }
}

.goods-name {
  font-size: 18px;

  font-weight: 600;
  line-height: 22px;
  // text-align: center;
  letter-spacing: 0px;
  width: 200px;
  // margin: 0 auto 12.4px auto;
  padding: 0 10px;
  color: #333333;
  // -webkit-text-stroke: #979797 0.7px;
  /* 浏览器可能不支持 */
}

.goods-desc {
  font-size: 14px;
  font-weight: normal;
  line-height: 17px;
  padding: 10px 10px 0;
  // text-align: center;
  letter-spacing: 0px;
  color: #666666;

  -webkit-text-stroke: #979797 0.7px;
  /* 浏览器可能不支持 */
}

.whiteSpace {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

}

.goods-price {
  font-weight: normal;
  line-height: 30px;
  padding: 10px;
  // text-align: center;
  letter-spacing: 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .price {
    font-size: 25.2px;
    color: #f31947;
    -webkit-text-stroke: #979797 0.7px;
    /* 浏览器可能不支持 */
  }

  .user {
    display: flex;
    align-items: center;

    .user-name {
      font-size: 15.5px;
    }
  }


  .state {
    font-size: 16.2px;
  }

}

.goods-type-line {
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  max-width: 1200px;
}

.goods-type-title {
  font-size: 31px;
  font-weight: normal;
  line-height: 37px;
  letter-spacing: 0px;
  color: #333333;
}

.active {
  color: #f31947;
}

.goods-type-labels {
  cursor: pointer;
  font-size: 21px;
  font-weight: normal;
  line-height: 25px;
  letter-spacing: 0px;
  margin-top: 10px;
  // border-bottom: 1px solid #a09c9c;
  // padding: 10px 0;
  // border: 1px solid #a09c9c;
  // border-bottom: 0;
  // width: 100%;
}

.goods-type-item {
  margin-left: 28px;
}

.time {
  font-size: 14px;
  font-weight: bold;
}

.content {
  padding-left: 5px;
}

.active {
  color: #f31947;
}

.expired {
  color: #999;
}

.QRCode {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;

  .QRImg {
    width: 150px;
    height: 150px;
    border: #333333 1px solid;
    border-radius: 5px;
    margin-bottom: 15px;
  }
}

.QRflex {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

::v-deep .ivu-modal-wrap1 .ivu-modal {
  top: calc(50% - 150px) !important;
}

.goods-type-wrapper {
  min-height: 920px !important;
  position: relative;
}

.goodsButton {
  width: 100%;
  height: 50px;
  display: flex;
  position: absolute;
  bottom: 0;
  justify-content: center;
  align-items: center;
}
</style>
<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
  padding: 3px 8px;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
